<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/29
 * Time: 16:36
 */

namespace HiCommon\Service;


use HiCommon\Repository\MessageRepository;
use HiCommon\Repository\UsersAppriseRepository;
use HiCommon\Repository\LogRepository;

class MessageServce extends BaseService
{


    /**
     *  添加消息通知记录
     *  hinq 2019 12 02
     *
     **/
    public function add_message(array $arr_input)
    {
        try {
            $temp = self::checkData((array)$arr_input);
            $data['title'] = $temp['title'];
            if (!empty($temp['img'])) {
                $data['img'] = $temp['img'];
            }
            $data['content'] = $temp['content'];
            $data['pid'] = $temp['pid'];
            $data['type'] = $temp['type'];
            $data['status'] = 1;
            $data['is_read'] = 0;
            $data['link_id'] = $temp['link_id'];
            $data['user_id'] = $temp['user_id'];
            $data['shop_id'] = $temp['shop_id'];
            $res = MessageRepository::add_one((array)$data);
            if (empty($res)) {
                return hello_error('添加失败');
            }
            //推送信息 向指定的用户推送一条消息通知

            return hello_success('ok');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *  验证传递过来的数据
     *  hinq 2019 12 02
     *
     **/
    public function checkData(array $arr_input)
    {
        return $arr_input;
    }


    /**
     *  统计指定用户的消息数量
     *  hinq 2020 5 18
     *
     **/
    public function get_message_count(){
        try{

            $user_id = api_user_id();
            $arr_where['user_id'] = $user_id;
            $arr_where['is_read'] = 0;

            $arr_where['pid'] = 1;
            $sys_count = LogRepository::count_where( (array) $arr_where );   //系统消息统计

            $arr_where['pid'] = 2;
            $activity_count = LogRepository::count_where( (array) $arr_where );     //活动消息统计

            $arr_where['pid'] = 3;
            $order_count = LogRepository::count_where( (array) $arr_where );            //订单消息统计
            $arr_count = [
                'sys_count' => $sys_count,
                'activity_count' => $activity_count,
                'order_count' => $order_count,
            ];
            return hello_success( 'ok' , $arr_count );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }


    /**
     *  获取指定的用户指定类型的系统消息
     *  hinq 2019 12 02
     *
     **/
    public function get_message(array $arr_input)
    {
        try {
            $user_id = api_user_id();
            $arr_input['user_id'] = $user_id;
            $arr_list = LogRepository::get_message_list( (array) $arr_input )->toarray();
            if( $arr_input['pid'] == 1  ){   //獲取系統消息
                foreach ( $arr_list['data'] as $key=>$vo){  //每次获取消息列表时  都将系统消息设置为已读
                    if( $vo['pid'] == 1 ){
                        LogRepository::update_message( (array) ['_id'=> $vo['_id']] ,(array) ['is_read'=>1]);  //我思考样写业这  why？  time can give yous answer
                    }
                }
            }
            return hello_success('ok', list_page_data_for_api($arr_list));
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *  修改指定的类型或指定数据的阅读状态
     *  hinq 2019 12 03
     *
     **/
    public function change_message( array $arr_input ){
        try {
            $user_id = api_user_id();
            $where['user_id'] = $user_id;
            $where['_id'] = $arr_input['_id'];
            $res = LogRepository::update_message( (array) $where , (array) ['is_read'=>1]);
            if( empty( $res) ){
                return hello_error('修改失败');
            }
            return hello_success('ok');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     *  添加订单评论信息(评论)
     *  hinq 2020 1 7
     *  $arr_input['order_id'] = '';   //当前评论关联的订单id
     *  $arr_input['goods_id'][] = '';   //当前评论关联的订单的商品id
     *  $arr_input['shop_id'] = '';    //当前评论关联的订单的商品所属门店的id
     *  $arr_input['type'] = '';       //11: 预约订单   12: 商品订单   13：积分订单
     **/
    public function apprise_create_more( array $arr_input  ){
        \DB::beginTransaction();      //开启事物
        try{
            $user_id = api_user_id();
            $arr_temp = json_decode( $arr_input['params'] , true );  //前端提交过来的数据是加密的  这里获取到的是一个数组

            //这个循环验证数据的有效性
            $where['user_id'] = $user_id;
            foreach ( $arr_temp as $key => $vo) {
                if( !empty( $vo['content'] ) && strlen(  $vo['content'] ) > 300  ){
                    return hello_error('评论内容不能超过300个字符');
                }
                $sensitive = sensitive( $arr_input['content'] );
                if( $sensitive ){
                    return hello_error('评论内容不能含有敏感词');
                }

                if( empty( $vo['score'] ) ){
                    return hello_error('分数不能为空');
                }
                $where['shop_id'] = $vo['shop_id'];
                $where['order_id'] = $vo['order_id'];
                $count = UsersAppriseRepository::get_count_by_where((array) $where );
//                if( $count >= 1 ){
//                    return hello_error('该订单已评论，请勿重复评论');
//                }
            }
            //这个循环添加数据到数据库
            $data['user_id'] = $user_id;
            $res = true;
            $res2 = true;
            $res4 = true;
            $shop_id = '';

            foreach ( $arr_temp as $key => $vo){
                $data['type'] = $vo['type'];            //订单类型  11: 预约订单   12: 商品订单   13：积分订单  14:服务订单
                $data['shop_id'] = $vo['shop_id'];      //门店的id
                $data['order_id'] = $vo['order_id'];    //订单的id
                $data['goods_id'] = $vo['goods_id'];    //商品的id
                $data['content'] = empty( $vo['content'] ) ? '此用户没有填写评论内容。' : $vo['content'] ;  //评论的内容
                $data['score'] = $vo['score'];  //评论的订单的凭分分数
                $img = '';
                if( !empty(  $vo['img'] ) ){
                    $img  = implode( $vo['img'] ,',');  //将提交的图片按逗号拼接到一起
                }
                $data['images'] = $img;  //评论的图片， 多个用逗号隔开
                //添加评论信息

                $res = UsersAppriseRepository::add_one( (array) $data );

                // 评论成功后将订单的状态修改为已评价
                  //服务订单  普通订单
                    $res2 = \Modules\Api\Service\PublicService::update_order_status( (int) $vo['type'] , (int) $vo['order_id']);

                    //获取评论的订单商品价格信息
//                 $where_goods = ['store_order_id' => $vo['order_id'] , 'goods_id' =>$vo['goods_id'] ];
                    $where_goods = ['id' => $vo['order_goods_id'] ];
                    $arr_option_goods['field'] = ['goods_amount','id'];
                    $goods_info = \HiCommon\Repository\StoreOrderGoodsRepository::get_one_by_where( (array) $where_goods , (array) $arr_option_goods );

                    //给用户添加购买商品获得的积分
                    $arrInput['user_id'] = $user_id;    //用户id
                    $arrInput['total_fee'] = $goods_info['goods_amount'];    //支付金额
                    $arrInput['type'] = 1;
                    $arrInput['order_id'] = $vo['order_id'];
                    $arrInput['order_type'] = 3;
                    $arrInput['remarks'] = '评论订单获得积分';
                    $res4 = PublicService::user_integral_change((array)$arrInput);
                $shop_id = $vo['shop_id'];
            }
            //统计当前商店的评分平均数
            $avg_num = UsersAppriseRepository::get_avg_to_where( (array) ['shop_id'=>$shop_id ] , (string) 'score' );  //获取指定门店所有的评论的平均值
            $res3 =  \HiCommon\Repository\ShopRepository::edit_one( (array) ['id'=>$shop_id , 'score' => round( $avg_num , 2 ) ]);  //将平均分同步到门店

            if(  $res && $res2 && $res3 ){
                \DB::commit();    //多个sql执行没有问题  提交所有的sql
                return hello_success('ok');
            }
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return hello_error( $exception->getMessage() );
        }
    }

    /**
     *  添加订单评论信息(单条评论)
     *  hinq 2020 1 7
     *  $arr_input['order_id'] = '';   //当前评论关联的订单id
     *  $arr_input['goods_id'] = '';   //当前评论关联的订单的商品id
     *  $arr_input['shop_id'] = '';    //当前评论关联的订单的商品所属门店的id
     *  $arr_input['type'] = '';       //11: 预约订单   12: 商品订单   13：积分订单  14:服务订单  15:道路救援订单
     **/
    public function apprise_create( array $arr_input ){
        try{

            \DB::beginTransaction();      //开启事物
            if( !empty( $arr_input['content'] ) && strlen(  $arr_input['content'] ) > 300  ){
                return hello_error('评论内容不能超过300个字符');
            }
            if( isset( $arr_input['img'] ) && !( count( $arr_input['img'] ) <= 3 )  ){
                return hello_error('图片只能上传1-3张');
            }
            $sensitive = sensitive( $arr_input['content'] );
            if( $sensitive ){
                return hello_error('评论内容不能含有敏感词');
            }
            $images ='';
            if( isset( $arr_input['img'] ) && count( $arr_input['img'] ) > 0 ){
                $images = implode(',',$arr_input['img']);
            }

            if( !in_array( $arr_input['score']  , [ 1 , 2 , 3 , 4 , 5 ] ) ){  //评论的分数不能为0
                return hello_error('评分错误');
            }
            //这里需要加一个逻辑  同一个用户对同一种类型的同一个订单的同一个产品只能评价一次
            $user_id = api_user_id();
            $where['user_id'] = $user_id;              //用户id
            $where['shop_id'] = $arr_input['shop_id'];          //店铺id
            $where['order_id'] = $arr_input['order_id'];        //订单id

            $count = UsersAppriseRepository::get_count_by_where((array) $where );   //通过条件统计是否已经评论
            if( $count >= 1 ){
                return hello_error('该订单已评论，请勿重复评论');
            }

            unset( $arr_input['img'] );
            $arr_input['content'] =  empty( $arr_input['content'] ) ? '此用户没有填写评论内容。' : $arr_input['content'];  //评论的内容允许为空
            $arr_input['goods_id'] =  empty( $arr_input['goods_id'] ) ? 0 : $arr_input['goods_id'];  //评论的内容允许为空
            $arr_input['images'] =  $images;   //评论的图片（最多只能能够上传3张图片）
            $arr_input['user_id'] =  $user_id;
            $res = UsersAppriseRepository::add_one( (array) $arr_input );   //添加评论信息

            //这里需要添加一个逻辑  评论成功后需要将订单的状态修改掉
            $res2 = true;
            $res4 = true;
            $arrInput['user_id'] = $user_id;    //用户id
            $arrInput['type'] = 1;
            $arrInput['order_id'] = $arr_input['order_id'];
            $arrInput['remarks'] = '评论订单获得积分';



            if( $arr_input['type'] == 15 ){  //道路救援订单
                $res2 = \HiCommon\Repository\RoadRescueOrderRepository::edit_one( (array) [ 'id'=>$arr_input['order_id'] , 'status'=>3 ] );
                //获取评论的订单商品价格信息
                $where_goods = ['id' => $arr_input['order_id'] ];
                $arr_option_goods['field'] = ['price','id'];
                $goods_info = \HiCommon\Repository\RoadRescueOrderRepository::get_one_where( (array) $where_goods , (array) $arr_option_goods );
                //给用户添加购买商品获得的积分
                $arrInput['total_fee'] = $goods_info['price'];    //支付金额
                $arrInput['order_type'] = 5;

            }else if( $arr_input['type'] == 11 ){  // 预约订单
                $res2 = \Modules\Api\Service\CheckpointOrderService::notify_apprise_order( (int) $arr_input['order_id']);

                //获取评论的订单商品价格信息
                $where_goods = ['id' => $arr_input['order_id'] ];
                $arr_option_goods['field'] = ['price','id'];
                $goods_info = \HiCommon\Repository\OrderCheckpointRepository::get_one_by_where( (array) $where_goods , (array) $arr_option_goods );
                //给用户添加购买商品获得的积分
                $arrInput['total_fee'] = $goods_info['price'];    //支付金额
                $arrInput['order_type'] = 2;

            }else{   //服务订单  普通订单
                $res2 = \Modules\Api\Service\PublicService::update_order_status( (int) $arr_input['type'] , (int) $arr_input['order_id']);
                //给用户添加购买商品获得的积分

                if( $arr_input['type'] == 12 ){
                    //获取评论的订单商品价格信息
                    $where_goods = ['store_order_id' =>$arr_input['order_id'] , 'goods_id' =>$arr_input['goods_id'] ];
                    $arr_option_goods['field'] = ['goods_amount','id'];
                                        //给用户添加购买商品获得的积分
                    $goods_info = \HiCommon\Repository\StoreOrderGoodsRepository::get_one_by_where( (array) $where_goods , (array) $arr_option_goods );

                    $arrInput['total_fee'] = $goods_info['goods_amount'];    //支付金额
                    $arrInput['order_type'] = 3;
                }else{
                    //获取评论的订单商品价格信息
                    $where_goods = ['id' => $arr_input['order_id'] ];
                    $arr_option_goods['field'] = ['pay_price','id'];
                    $goods_info = \HiCommon\Repository\OrderRepairstoreRepository::get_one_by_where( (array) $where_goods , (array) $arr_option_goods );

                    $arrInput['total_fee'] = $goods_info['pay_price'];    //支付金额
                    $arrInput['order_type'] = 4;
                }
            }
            $res4 = \HiCommon\Service\PublicService::user_integral_change((array)$arrInput);
            //统计当前商店的评分平均数
            $avg_num = UsersAppriseRepository::get_avg_to_where( (array) ['shop_id'=>$arr_input['shop_id']] , (string) 'score' );   //获取指定们门店下的所有评论的平均值
            $res3 =  \HiCommon\Repository\ShopRepository::edit_one( (array) ['id'=>$arr_input['shop_id'] , 'score' => round( $avg_num , 2 ) ]);  //将平均分数同步到门店

            if(  $res && $res2 && $res3 && $res4){
                \DB::commit();    //多个sql执行没有问题  提交所有的sql
                return hello_success('ok');
            }
            return hello_error('评论失败');
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *  获取指定门店下的所有评论数据(或者指定数量的带图片的数据)
     *  hinq 2020 3 24
     *
     **/
    public function get_shop_apprise( array $arr_input ){
        try{
           $arr_option['where'] = ['shop_id'=>$arr_input['shop_id']];       //店铺id
           if( !empty( $arr_input['per_page'] ) ){  //门店的详情页获取指定条数数据 ， 此地方获取的数据是评论内容里面必须包含图片
               $arr_option['n_per_page'] = $arr_input['per_page'];   //获取指定条数数据
           }
           $arr_option['with'] = ['user','user.user_vehicle'=>function( $query ){
               $query->select('id','user_id','plate_no','brand_model');
           }];
           $arr_option['field'] = ['id','content','score','images','user_id','created_at'];
           $arr_option['order'] = ['key'=>'id' , 'value'=>'desc'];
           $arr_list = UsersAppriseRepository::get_list( (array) $arr_option )->toarray();
           $temp = [];
           foreach ( $arr_list['data'] as $key=>$item ){
               $temp[$key]['id'] = $item['id'];
               $temp[$key]['content'] = empty($item['content']) ? '此用户没有填写评论内容。' : $item['content'];
               if( empty( $item['images'] ) ){
                   $temp[$key]['images'] = [];
               }else{
                   $item['images'] =  explode( ',' , $item['images']);
                   foreach ( $item['images'] as $k => $v ){  //将图片的路径转成绝对路径
                       $temp[$key]['images'][] = oss_full_url( $v );
                   }
               }
               $temp[$key]['score'] = $item['score'];   //评价的分数
               $temp[$key]['created_at'] = $item['created_at'];     //评论的时间
               $temp[$key]['nickname'] = $item['user']['nickname'];     //评价的用户昵称
               $temp[$key]['user_id'] = $item['user']['id'];        //用户id
               $temp[$key]['head_img'] = $item['user']['head_img']['full_src'];     //评价的用户头像
               $temp[$key]['car_name'] = $item['user']['user_vehicle']['brand_model'];      //用户的车辆类型名称
               $temp[$key]['car_plate_no'] = $item['user']['user_vehicle']['plate_no'];     //用户车辆的拍照
               $temp[$key]['car_id'] = $item['user']['user_vehicle']['id'];     //车辆信息
           }

            $data = [
                'page_data' =>[
                    'current_page' => $arr_list['current_page'],
                    'last_page' => $arr_list['last_page'],
                    'per_page' => $arr_list['per_page'],
                    'total' => $arr_list['total'],
                ],
                'data' => $temp
            ];
           return hello_success('ok',$data);
        }catch (\Exception $exception){
            return hello_error($exception->getMessage());
        }
    }




    /**
     *  按条件获取指定的评论列表
     *  hinq 2020 1 6
     *  id  指定的类型id
     *  type  1：订单id   2：商品id   3：门店id
     **/
    public function apprise_list( array $arr_input ){
         try{
             $act = empty( $arr_input['act'] ) ? 1 : $arr_input['act'];

             if( $act == 1 ){           //
                 $arr_option['where'] = ['type'=>$arr_input['type'] , 'order_id' =>$arr_input['id'] ];
             }else if( $act == 2 ){     //
                 $arr_option['where'] = ['type'=>$arr_input['type'] , 'goods_id' =>$arr_input['id'] ];
             }else if( $act == 3 ){     //
                 $arr_option['where'] = [ 'shop_id' =>$arr_input['id'] ];
             }
             $arr_option['field'] = ['id','user_id','content','images','created_at'];
             $arr_option['with'] = ['user','user.user_vehicle'=>function( $query ){
                 $query->select('id','user_id','plate_no','brand_model');
             }];
             $arr_list = UsersAppriseRepository::get_list( (array) $arr_option )->toarray();

             foreach ( $arr_list['data'] as $key=>&$vo){
                 unset( $vo['extend'] );  //释放多余的字段
                 if( empty( $vo['images'] ) ){
                     $vo['images'] = [];
                 }else{
                     $vo['images'] = explode(',',$vo['images']);
                     foreach ( $vo['images']  as &$item ){
                         $item = oss_full_url( $item );
                     }
                 }
                 $vo['nickname'] = $vo['user']['nickname'];
                 $vo['head_img'] = $vo['user']['head_img']['full_src'];
                 $vo['created_at'] = date('Y-m-d' , strtotime( $vo['created_at'] ) );
                 $vo['plate_no'] = $vo['user']['user_vehicle']['plate_no'];
//                 $vo['brand'] = $vo['user']['user_vehicle']['brand'];
                 $vo['brand_model'] = $vo['user']['user_vehicle']['brand_model'];
                 unset( $vo['user'] );
             }
             $data = [
                 'page_data' =>[
                     'current_page' => $arr_list['current_page'],
                     'last_page' => $arr_list['last_page'],
                     'per_page' => $arr_list['per_page'],
                     'total' => $arr_list['total'],
                 ],
                 'data' => $arr_list['data']
             ];
             return hello_success('ok',$data);
         }catch (\Exception $exception ){
             return ['state' => 1, 'msg' => $exception->getMessage()];
         }
    }

    /**
     *  获取指点商品的评论列表
     *  hinq 2020 3 26
     *
     **/
    public function apprise_to_goods( array $arr_input , $act = null ){
        try{
            $user_id = api_user_id();
            if( empty( $act ) ){
                $arr_option['where'] = [ 'type'=>$arr_input['type'] , 'goods_id' => $arr_input['goods_id']];
            }else{
                $arr_option['where'] = [ 'type'=>$arr_input['type'] , 'shop_id' => $arr_input['shop_id']];
            }
            $arr_option['field'] = ['id','content','images','user_id','created_at','score'];
            $arr_option['with'] = ['user'];
            $arr_option['n_per_page'] = $arr_input['per_page'];
            //获取指定商品下所有的评论
            $arr_list = UsersAppriseRepository::get_list( (array) $arr_option )->toarray();
            foreach ( $arr_list['data'] as $key => &$vo ){
                $vo['content'] = empty( $vo['content'] ) ? '此用户没有填写评论内容。' : $vo['content'];  //评论内容允许为空，给默认值
                $vo['nickname'] = $vo['user']['nickname'];   //用户昵称
                $vo['head_img'] = $vo['user']['head_img']['full_src'];  //用户的图像(绝对路径)
                unset( $vo['user'] );
                if( !empty( $vo['images'] ) ){
                    $images = explode( ',' , $vo['images'] );
                    $vo['images'] = $images;
                    foreach ( $vo['images'] as $k => &$v ){
                        $v = oss_full_url( $v );  //将图片的路径转换为绝对路径
                    }
                }else{
                    $vo['images'] = [];
                }
            }
            $data = [
                'page_data' =>[
                    'current_page' => $arr_list['current_page'],
                    'last_page' => $arr_list['last_page'],
                    'per_page' => $arr_list['per_page'],
                    'total' => $arr_list['total'],
                ],
                'data' => $arr_list['data']
            ];
            return hello_success('ok',$data);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }
}
